<?php

namespace App\Http\Controllers\Pay;

use App\Api\Controllers\Merchant\OrderController;
use App\Http\Controllers\Controller;
use App\Models\Store;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\Order;

use App\Api\Controllers\Merchant\PayBaseController;

class PayController extends Controller{
    
    //推送消息
    private function send($message)
    {
        try {
            $webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d9ed60d3-a4a0-4aee-b335-6b90b8b1a4dc";
            $data = [
                'msgtype' => 'markdown',
                'markdown' => [
                    'content' => $message
                ]
            ];
            $data_string = json_encode($data);
            $result = $this->request_by_curl($webhook, $data_string);
            $result = json_decode($result, true);
            if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
                return false;
            }
            if ($result['errcode'] != 0) {
                return false;
            }
            return true;

        }catch (\Exception $e){

        }
    }

    private function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    
    public function order_query(){
        // file_put_contents('sdfdass.log',var_export(time(),true)."\r\n",FILE_APPEND);
        // $obj = DB::table('orders');
        // $where[] = ['created_at', '>=', date("Y-m-d 00:00:00",strtotime("now"))];
        // $where[] = ['created_at', '<=', date("Y-m-d 23:59:59",strtotime("now"))];
        // $token = JWTAuth::attempt(array('phone'=>'18605581186','password'=>'WFT1603.'));
        
        // $order=$obj->where($where)->whereIn('pay_status', [2])->get();
        // $order=json_decode($order,true);
        // foreach($order as $key1=>$val1){
        //     $post_data=array(
        //         'store_id'=>$val1['store_id'],
        //         'out_trade_no'=>$val1['out_trade_no'],
        //         'token'=>$token
        //     );
        //     $res=$this->http_curl('https://pay.zgjindoufu.com/api/basequery/update_order', json_encode($post_data));
        //     $res=json_decode($res,true);
        //     file_put_contents('b5366546.log',var_export($res,true)."\r\n",FILE_APPEND);
        //     if($res['pay_status']=='3' ||$val['dk_jf']>='15'){
        //         $Device = DB::table('devices')->where('store_id', $val1['store_id'])->whereIn("device_type", ['v_car_CG02','v_whty'])->get();
        //         foreach ($Device as $key=>$val){
        //             //博实结
        //             if ($val->device_type == "v_car_CG02") {
        //                 $broadCastType = 24;
        //                 $out_order_id=$val1['out_trade_no'];
        //                 $params=array(
        //                     'appId'=>'ZF441',
        //                     'timestamp'=>time().'000',
        //                     'requestId'=>$out_order_id,
        //                     'userCode'=>'ZF441',
        //                 );

        //                 $tokenString='';
        //                 ksort($params);
        //                 foreach ($params as $k=>$v){
        //                     $tokenString.=$k.$v;
        //                 }
        //                 $token=strtoupper(md5($tokenString.'2022bsjZF441EYN'));
        //                 Order::where('out_trade_no', $val1['out_trade_no'])->update(array('status'=>3,'pay_status'=>3,'pay_status_desc'=>'支付失败'));
        //                 $params['token']=$token;
        //                 $params['devName']=$val->device_no;
        //                 $params['money']=$val1['total_amount'];
        //                 $params['broadCastType']=$broadCastType;
        //                 $params_string=self::allin_Params($params);
        //                 $url='https://ioe.car900.com/v1/openApi/dev/controlDevice.json?'.$params_string;
        //                 $res=self::curl_merch($url,'GET',json_encode($params),array('Content-Type: application/json'));
        //             }
        //             //天喻
        //             if ($val->device_type == "v_whty") {
        //                 $post=array(
        //                     'accessKeyId'=>'IOT_ACCOUNT_PROD_MTIzNDU2Nzg5MA',
        //                     'requestId'=>$val1['out_trade_no'],
        //                     'timestamp'=>time().'000',
        //                     'deviceId'=>$val->device_no,
        //                     'content'=>'顾客取消支付'.$val1['total_amount'].'元'
        //                 );
        //                 ksort($post);
        //                 $stringA=$this->allin_Params($post);
        //                 $sign=base64_encode(hash_hmac('sha256', $stringA, 'cWF6c2RmcmU0NTZ5aHU3ODkwOWtmZ3J0c2ZmcjM0NDY1NDYzNDNkZ2ZnZmdmZXJlcg==',true));
        //                 $post['sign']=$sign;
        //                 $ch = curl_init();
        //                 curl_setopt($ch, CURLOPT_URL, 'https://voice.tysmartpos.com/api/bank/pushmsg');
        //                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //                 curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        //                     'Content-Type: application/json'
        //                 ));
        //                 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
                        
        //                 $result = curl_exec($ch);
        //                 curl_close($ch);
        
        //                 Order::where('out_trade_no', $val1['out_trade_no'])->update(array('status'=>3,'pay_status'=>3,'pay_status_desc'=>'支付失败'));
        //             }
        //         }
        //     }else{
        //         Order::where('out_trade_no', $val1['out_trade_no'])->update(array('dk_jf'=>$val['dk_jf']+1));
        //     }
        // }
    }
    
    public static function allin_Params(array $array){
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }
    
    //计划任务-拉取门店到代办任务
    public function wing_orders(){
        fastcgi_finish_request();
        //翼支付父子商户关系绑定接口
        // $date_time=date("Ymd",strtotime("-1 day"));
        $stores=DB::table('wing_stores')->where('is_binding','0')->get()->toArray();
        foreach ($stores as $k=>$v){
            $url='https://mapi.bestpay.com.cn/mapi/merchant_product/orgmerchant/verifyFileRelationAggregateCfg';
            $obj = new \App\Api\Controllers\lianfu\PayController();
            $data['traceLogId'] = 'wing'.time();//日志ID
            $data['agentsMerchantNo'] = '3178035630163868';//父商户号
            $data['platformMerchantNo'] = $v->merchantNo;//子商户号
            $data['operationBy'] = '18605581186';//交易金额
            $data['merchantNo'] = '3178035630163868';//条码信息
            $return = $obj->verifyFileRelationAggregateCfg($url,$data);
            $return=json_decode($return,true);
            if($return['success']){
                file_put_contents('b12313.log',var_export('___________',true)."\r\n",FILE_APPEND);
                file_put_contents('b12313.log',var_export($v->merchantNo,true)."\r\n",FILE_APPEND);
                file_put_contents('b12313.log',var_export($return,true)."\r\n",FILE_APPEND);
                DB::table('wing_stores')->where('id',$v->id)->update(array('is_binding'=>1));
            }else{
                file_put_contents('b123131.log',var_export('___________',true)."\r\n",FILE_APPEND);
                file_put_contents('b123131.log',var_export($v->merchantNo,true)."\r\n",FILE_APPEND);
                file_put_contents('b123131.log',var_export($return,true)."\r\n",FILE_APPEND);
            }
        }
        
    }
    
    //同步翼支付表格数据到订单表
    public function get_wing_csv(){
        $date=date('Ymd',time()-86400);
        $temp=base_path().'/public/bestpay/'.'bestpay'.$date.'_3178035630163868.csv';
        $file = fopen($temp, 'r');
        $keys = fgetcsv($file); // 获取列名作为键值
        $data = array();
        while (($row = fgetcsv($file)) !== false) {
            $data[] = eval('return '.iconv('gbk','utf-8',var_export($row,true)).';');
        }
        fclose($file);
        unset($data[0]);
        unset($data[1]);
        unset($data[2]);
        unset($data[3]);
        unset($data[4]);
        unset($data[5]);
        unset($data[6]);
        foreach ($data as $k=>$v){
            if(isset($v[1])){
                $order=DB::table('orders')->where('out_trade_no',trim($v[1]))->first();
                if(empty($order)){
                    if(strlen($v[13])<10){
                        if(strstr($v[5],'WECHATPAY')){
                          $ways_type='30050';
                          $ways_type_desc='微信支付';
                          $ways_source='weixin';
                          $ways_source_desc='微信支付';
                        }else if(strstr($v[5],'ALIPAY')){
                          $ways_type='30051';
                          $ways_type_desc='支付宝';
                          $ways_source='alipay';
                          $ways_source_desc='支付宝';
                        }else if(strstr($v[5],'QUICKPASS')){
                          $ways_type='30052';
                          $ways_type_desc='云闪付';
                          $ways_source='unionpay';
                          $ways_source_desc='云闪付';
                        }else{
                          $ways_type='30053';
                          $ways_type_desc='翼支付';
                          $ways_source='Bestpay';
                          $ways_source_desc='翼支付';
                        }
                        $store_id= DB::table('wing_stores')->where('merchantNo', trim($v[16]))->select('store_id')->first();
                        $store=DB::table('stores')->where('store_id', $store_id->store_id)->first();
                        if(empty($store->store_id)){
                            file_put_contents('bestpay_order_error.log',var_export($v,true)."\r\n",FILE_APPEND);
                        }else{
                            $order=array('config_id'=>'1234','out_trade_no'=>trim($v[1]),'trade_no'=>trim($v[1]),'store_id'=>$store->store_id,'merchant_name'=>'店长','user_id'=>$store->user_id,'merchant_id'=>$store->merchant_id
                            ,'store_name'=>$store->store_name,'ways_type'=>$ways_type,'rate'=>'0.35','ways_type_desc'=>$ways_type_desc,'ways_source'=>$ways_source,'ways_source_desc'=>$ways_source_desc,'pay_method'=>'app'
                            ,'company'=>'wingpay','total_amount'=>$v[7],'receipt_amount'=>$v[7],'buyer_pay_amount'=>$v[7],'pay_amount'=>$v[7],'fee_amount'=>$v[7]
                            ,'shop_price'=>$v[7],'shop_count'=>1,'status'=>1,'pay_status'=>1,'pay_status_desc'=>'支付成功','pay_time'=>$v[4],'created_at'=>$v[4],'updated_at'=>$v[4]);
                            DB::table('orders')->insert($order);
                            file_put_contents('bestpay_order_success.log',var_export($v,true)."\r\n",FILE_APPEND);
                        }
                    }
                }
            }
        }
    }
    
    public static function curl_merch($url,$method,$params,$header = []){
        //初始化CURL句柄
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if(!empty($header)){
            curl_setopt ( $curl, CURLOPT_HTTPHEADER, $header);
        }
        //请求时间
        $timeout = 30;
        curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
        switch ($method){
            case "GET" :
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                if(is_array($params)){
                    $params = json_encode($params,320);
                }

                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($curl, CURLOPT_POSTFIELDS,$params);
                break;
        }
        $data = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);//关闭cURL会话

        return $data;
    }
    
    function http_curl($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // post的变量
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data)
            )
        );
        $output = curl_exec($ch);
        curl_close($ch);

        //返回数据
        return $output;
    }
    
    //金额获取接口
    public function print(Request $request){
        $data = $request->getContent();
        $data=json_decode($data,true);
        $array=preg_replace('/[^\.0123456789:]/s', '', $data['print_content']);
        $array=explode(":",$array);
        foreach($array as $key=>$val){
            if (preg_match('/\.\d{2,}/', $val)) { 
                $money=$val;
            }
        }
        if(isset($money)){
            echo json_encode(array('code'=>'SUCCESS','msg'=>'成功','data'=>$money));
        }else{
            echo json_encode(array('code'=>'ERROR','msg'=>'失败','data'=>0.00));
        }
    }
    
    public function get_company(){
        fastcgi_finish_request();
        $stores=Db::table('store_list')->select('store_id')->limit(200)->get();
        $stores=json_decode($stores,true);
        $stores = array_column($stores, 'store_id');
        $this->cefenrun($stores);
        $this->store_count($stores);
        foreach ($stores as $k=>$v){
           Db::table('store_list')->where('store_id',$v)->delete();
        }
    }
    
    public function get_stores(){
        $stores=Db::table('stores')->select('store_id')->get();
        $stores=json_decode($stores,true);
        $stores = array_column($stores, 'store_id');
        foreach ($stores as $k=>$v){
            $arr=array(
                'store_id'=>$v,
            );
           Db::table('store_list')->insert($arr);
        }
    }
    
    public function recursion1($user_id,$i = 0){
        $user = DB::table('users')->where([ 'id' => $user_id ])->select('id', 'name', 'pid')->get();
        $user = json_decode($user,true);
        if( $user[0]['pid'] !== '0'){
            $_SESSION['users'][$i] = $user[0];
            $i++;
            $this->recursion1($user[0]['pid'],$i);
        }else{
            $_SESSION['users'][$i] = $user[0];
        }
        return json_encode((object)$_SESSION['users']);
    }
    
     //统计店铺数据
    public function store_count($storeids){
        // fastcgi_finish_request();
        $date_time=date("Y-m-d",strtotime("-1 day"));
        $stores=DB::table('stores')->whereIn('store_id',$storeids)->get();
        $stores=json_decode($stores,true);
        foreach($stores as $k=>$v){
            $store_id=$v['store_id'];
            file_put_contents('storecount2.log',var_export($store_id,true)."\r\n",FILE_APPEND);
            $store=DB::table('stores')->where(array('store_id'=>$store_id))->first();
            if($store->pid>0){
                $upstore=DB::table('stores')->where(array('id'=>$store->pid))->first();
            }
            $settling_day=$date_time;
            $where[] = ['created_at', '>=', $settling_day.' 00:00:00'];
            $where[] = ['created_at', '<=', $settling_day.' 23:59:59'];
            $time=strtotime($settling_day)+600;
            //总收款
            $total_amount=DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            if($total_amount>0){
                //总手续费
                $fee_amount=DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount');
                
                //总退款
                $refund_amount=DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount');
                
                //总收款笔数
                $total_num=count(DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->get());
                
                //总退款笔数
                $refund_num=count(DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->get());
                
                //微信收款总额
                $weixin_total_amount = DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'weixin')->select('total_amount')->sum('total_amount');
                
                //微信收款笔数
                $weixin_total_num = count(DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'weixin')->select('total_amount')->get());
                
                //支付宝收款金额
                $alipay_total_amount = DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'alipay')->select('total_amount')->sum('total_amount');
                
                //支付宝收款笔数
                $alipay_total_num = count(DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'alipay')->select('total_amount')->get());
                
                // 云闪付收款金额
                $unionpay_total_amount = DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->sum('total_amount');
                
                // 云闪付收款笔数
                $unionpay_total_num = count(DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'unionpay')->select('total_amount')->get());
                
                 // 翼支付收款金额
                $Bestpay_total_amount = DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->sum('total_amount');
                
                // 翼支付收款笔数
                $Bestpay_total_num = count(DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('ways_source', 'Bestpay')->select('total_amount')->get());
            }else{
                 //总手续费
                $fee_amount='0.00';
                //总退款
                $refund_amount='0.00';
                
                //总收款笔数
                $total_num= '0';
                
                //总退款笔数
                $refund_num= '0';
                
                //微信收款总额
                $weixin_total_amount ='0.00';
                
                //微信收款笔数
                $weixin_total_num =  '0';
                
                //支付宝收款金额
                $alipay_total_amount = '0.00';
                
                //支付宝收款笔数
                $alipay_total_num =  '0';
                
                // 云闪付收款金额
                $unionpay_total_amount = '0.00';
                
                // 云闪付收款笔数
                $unionpay_total_num =  '0';
                
                 // 翼支付收款金额
                $Bestpay_total_amount = '0.00';
                
                // 翼支付收款笔数
                $Bestpay_total_num = '0';
            }
            
            $arr=array(
                'store_amount'=>$total_amount-$refund_amount,
                'refund_amount'=>$refund_amount,
                'fee_amount'=>$fee_amount,
                'store_order_count'=>$total_num,
                'refund_order_num'=>$refund_num,
                'store_id'=> $store_id,
                'sub_storeid'=>$store->pid==0 ? 0 :$upstore->store_id,
                'settling_day'=>$settling_day,
                'weixin_amount'=>$weixin_total_amount,
                'weixin_num'=>$weixin_total_num,
                'alipay_amount'=>$alipay_total_amount,
                'alipay_num'=>$alipay_total_num,
                'unionpay_amount'=>!empty($unionpay_total_amount)?$unionpay_total_amount:0.00,
                'unionpay_num'=>$unionpay_total_num,
                'bestpay_amount'=>$Bestpay_total_amount,
                'bestpay_num'=>$Bestpay_total_num,
                'created_at'=>$time
            );

            DB::table('stores_day_count')->insert($arr);
            $where1['store_id']=$store_id;
            $merchant_stores = DB::table('merchant_stores')->where($where1)->select()->get();
            $merchant_stores=json_decode($merchant_stores,true);
            foreach($merchant_stores as $key=>$val){
                $merchant_amount = DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('merchant_id', $val['merchant_id'])->select('total_amount')->sum('total_amount');
                if($merchant_amount>0){
                    $merchant_num = count(DB::table('orders')->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6])->where('merchant_id', $val['merchant_id'])->select('total_amount')->get());
                    $mer=array(
                        'store_id'=>$store_id,
                        'merchant_id'=>$val['merchant_id'],
                        'merchant_money'=>$merchant_amount,
                        'merchant_num'=>$merchant_num,
                        'created_at'=>$time,
                        'settling_day'=>$settling_day,
                    );
                    DB::table('stores_cash_count')->insert($mer);
                }
            }
        }
    }
    
    public function cefenrun($store_ids){
        session_start();
        // fastcgi_finish_request();
        $date_time=date("Y-m-d",strtotime("-1 day"));
        $settling_day=$date_time;
        $time=strtotime($settling_day)+100;
        $where[] = ['created_at', '>=', $settling_day.' 00:00:00'];
        $where[] = ['created_at', '<=', $settling_day.' 23:59:59'];
        
        $company_config=DB::table('company_config')->whereIn('store_id',$store_ids)->get();
        //4：预充 3：通道扣费 2：代扣 1：服务费
        foreach($company_config as $k=>$v){
            file_put_contents('ceshif.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
            $user_id = DB::table('stores')->where([ 'store_id' => $v->store_id ])->value('user_id');
            unset($_SESSION['users']);
            $users = $this->recursion1($user_id);
            $users = json_decode($users, true);
            $users = array_reverse($users);
            unset($store);
            unset($p_stores);
            unset($store_ids);
            $store = DB::table('stores')->where('store_id', $v->store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
            
            $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
            if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                $store_ids[0] = $store->store_id;
                $p_stores = json_decode($p_stores, true);
                foreach($p_stores as $k1 => $v1){
                    $pay_ways=DB::table('store_pay_ways')->where('store_id', $v1['store_id'])->where('company', $v->company)->where('status', 1)->select('company')->distinct()->first();
                    if(empty($pay_ways)){
                        $store_ids[] = $v1['store_id'];
                    }
                }
            }else{
                $store_ids[0] = $store->store_id;
            }
            $total_amount=DB::table('orders')->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
            if($total_amount>0){
                $total_num=DB::table('orders')->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->count('total_amount');
                $refund_amount=DB::table('orders')->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->where('pay_status', 6)->select('refund_amount')->sum('refund_amount');
                
                $total_amount1=$total_amount;
                $total_amount=$total_amount-$refund_amount;
                
                if($v->model==4){
                    foreach($users as $key=>$val){
                        $user_rates=DB::table('user_rates')->where('user_id', $val['id'])->where('company',$v->company)->first();
                        $fee_amount=round(($total_amount/100)*$v->configure_channel_fee,2);
                        $basic_money=round(($total_amount/100)*$user_rates->yu_rate,2);
                        $commission_money=$fee_amount-$basic_money;
                        
                        if($commission_money<0){
                            $commission_money='0.00';
                        }
                        
                        if($user_rates->yu_rate==$v->configure_channel_fee){
                            $commission_money='0.00';
                            $fee_amount='0.00';
                        }
                        $arr=array(
                            'company'=>$v->company,
                            'store_id'=>$v->store_id,
                            'total_amount'=>$total_amount1,
                            'fee_amount'=>$fee_amount,
                            'basic_money'=>$basic_money,
                            'commission_money'=> $commission_money,
                            'settling_day'=>$settling_day,
                            'is_rate'=>0,
                            'created_at'=>$time,
                            'total_num'=>$total_num,
                            'refund_amount'=>$refund_amount,
                            'user_id'=>$val['id']
                        );
                        DB::table('company_day_commission')->insert($arr);
                    }
                }else if($v->model==3){
                    
                    foreach($users as $key=>$val){
                        $user_rates=DB::table('user_rates')->where('user_id', $val['id'])->where('company',$v->company)->first();
                        if($v->company=='vbill'){
                            $fee_amount=round(($total_amount/100)*$v->configure_channel_fee,2);
                        }else{
                            $fee_amount=DB::table('orders')->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->where('pay_status', 1)->select('fee_amount')->sum('fee_amount');
                        }
                        $basic_money=round(($total_amount/100)*$user_rates->rate,2);
                        $commission_money=$fee_amount-$basic_money;
                        if($commission_money<0){
                            $commission_money='0.00';
                        }
                        if($user_rates->rate==$v->configure_channel_fee){
                            $commission_money='0.00';
                            $fee_amount='0.00';
                        }
                        $arr=array(
                            'company'=>$v->company,
                            'store_id'=>$v->store_id,
                            'total_amount'=>$total_amount1,
                            'fee_amount'=>$fee_amount,
                            'basic_money'=>$basic_money,
                            'commission_money'=> $commission_money,
                            'settling_day'=>$settling_day,
                            'is_rate'=>0,
                            'created_at'=>$time,
                            'total_num'=>$total_num,
                            'refund_amount'=>$refund_amount,
                            'user_id'=>$val['id']
                        );
                        DB::table('company_day_commission')->insert($arr);
                    }
                }else if($v->model==2){
                    foreach($users as $key=>$val){
                        $user_rates=DB::table('user_rates')->where('user_id', $val['id'])->where('company',$v->company)->first();
                        $fee_amount=DB::table('orders')->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->where('pay_status', 1)->select('fee_amount')->sum('fee_amount');
                        $basic_money=round(($total_amount/100)*$user_rates->era_rate,2);
                        $commission_money=$fee_amount-$basic_money;
                        if($commission_money<0){
                            $commission_money='0.00';
                        }
                        if($user_rates->era_rate==$v->configure_channel_fee){
                            $commission_money='0.00';
                            $fee_amount='0.00';
                        }
                        $arr=array(
                            'company'=>$v->company,
                            'store_id'=>$v->store_id,
                            'total_amount'=>$total_amount1,
                            'fee_amount'=>$fee_amount,
                            'basic_money'=>$basic_money,
                            'commission_money'=> $commission_money,
                            'settling_day'=>$settling_day,
                            'is_rate'=>0,
                            'created_at'=>$time,
                            'total_num'=>$total_num,
                            'refund_amount'=>$refund_amount,
                            'user_id'=>$val['id']
                        );
                        DB::table('company_day_commission')->insert($arr);
                    }
                }else if($v->model==1){
                    
                    foreach($users as $key=>$val){
                        $user_rates=DB::table('user_rates')->where('user_id', $val['id'])->where('company',$v->company)->first();
                        $fee_amount=round(($total_amount/100)*$v->configure_channel_fee,2);
                        $basic_money=round(($total_amount/100)*$user_rates->server_rate,2);
                        $commission_money=$fee_amount-$basic_money;
                        if($commission_money<0){
                            $commission_money='0.00';
                        }
                        if($user_rates->server_rate<=$v->configure_channel_fee){
                            $commission_money='0.00';
                            $fee_amount='0.00';
                        }
                        $arr=array(
                            'company'=>$v->company,
                            'store_id'=>$v->store_id,
                            'total_amount'=>$total_amount1,
                            'fee_amount'=>$fee_amount,
                            'basic_money'=>$basic_money,
                            'commission_money'=> $commission_money,
                            'settling_day'=>$settling_day,
                            'is_rate'=>0,
                            'created_at'=>$time,
                            'total_num'=>$total_num,
                            'refund_amount'=>$refund_amount,
                            'user_id'=>$val['id']
                        );
                        DB::table('company_day_commission')->insert($arr);
                    }
                }
            }
        }
        unset($users);
    }
    
    //支付接口&退款
    public function authcode(Request $request){
        $data = $request->getContent();
        $data=json_decode($data,true);
        
    }
    
    //支付查询接口
    public function queryorder(Request $request){
        $data = $request->getContent();
        $data=json_decode($data,true);
        echo '<pre>';
        print_r(111);
        die;
    }
    
    //校验md5
    public function checks_md5($data, $secret_key){
        try {
//            $key = '88888888';
            $key = $secret_key;
            $sign = $data['sign'];
            unset($data['sign']);
            $string = $this->getSignContent($data).'&key='.$key;
            
            if ($sign == md5($string)) {
                return [
                    'return_code' => 'SUCCESS',
                    'return_msg' => '验证通过'
                ];
            } else {
                return [
                    'return_code' => 'FALL',
                    'return_msg' => '验证不通过'
                ];
            }
        } catch (\Exception $ex) {
            return [
                'return_code' => 'FALL',
                'return_msg' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }
    
    //参数拼接
    public function getSignContent($params){
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            //空值和数组,不参与签名组串
            if (is_array($v) || true === $this->checkEmpty($v)) {
                continue;
            }
            $v = $this->characet($v, "UTF-8"); // 转换成目标字符集
//            print_r($v);die;
            if ($i == 0) {
                $stringToBeSigned .= "$k" . "=" . "$v";
            } else {
                $stringToBeSigned .= "&" . "$k" . "=" . "$v";
            }
            $i++;
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }
    
    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value){
        $value = trim($value);

        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if ($value === "")
            return true;
        if ($value === [])
            return true;
        if (empty($value))
            return true;

        return false;
    }
    
    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset){
//        print_r($data);die;
        if (!empty($data)) {
            $fileType = "UTF-8";
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset);
//				$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }

        return $data;
    }
    
    public function get_commany_name($commany_name){
        if($commany_name=='alipay'){
            $commany_name_zw='官方支付宝';
        }else if($commany_name=='weixin'){
            $commany_name_zw='官方微信';
        }else if($commany_name=='vbill'){
            $commany_name_zw='随行付';
        }else if($commany_name=='wftpay'){
            $commany_name_zw='徽商银行';
        }else if($commany_name=='hwcpay'){
            $commany_name_zw='汇旺财';
        }else if($commany_name=='nongjin'){
            $commany_name_zw='农商行';
        }else if($commany_name=='abc'){
            $commany_name_zw='农行BMP';
        }else if($commany_name=='wingpay'){
            $commany_name_zw='翼支付';
        }else if($commany_name=='pingan'){
            $commany_name_zw='平安银行';
        }else{
            $commany_name_zw='其它';
        }
        return $commany_name_zw;
    }
    
    public function get_invoice(Request $request){
        //接参
        $data = $request->getContent();
        $data = json_decode($data, true);
        $trade_no=$data['out_trade_no'];
        $order=Db::table('orders')->where(['trade_no'=> $trade_no])->first();
        if(!empty($order)){
            $pay_obj = new PayBaseController();
            $billing = $pay_obj->billing($order->out_trade_no); // 开票地址
            $billing = json_decode($billing, true);
            if($billing['code'] == 'E0000'){
                $url = $billing['result']['ewmUrl'];
                return json_encode(array('status'=>1,'invoice_url'=>$url));
            }else{
                return json_encode(array('status'=>2,'invoice_url'=>''));
            }
        }else{
            return json_encode(array('status'=>2,'invoice_url'=>''));
        }
        
        // file_put_contents('nuonuopos.log',var_export($data,true)."\r\n",FILE_APPEND);
        
        // $url='http://nnfpbox.nuonuocs.cn/invoice/scan/k.do?jc=NzA1NDA4ODA1NDA4MXJ6enJqcw==&on=MjExOTEyMDA4NzEwMjExNjA1MDA0ODA1MDA1MDA0ODA1NzA1MTA0ODA0OTA1MzA1MTA1MzA0OTA1NzA1NTA0ODA1NjA1MTA1MDA0ODA1NG5sbG5sbg==&flag=MDA5OTEwODEwNTEwMWJibGJiaw==';
        
        
        
        // // 诺诺开票
        // $pay_obj = new PayBaseController();
        // $billing = $pay_obj->billing($tra_data_arr['data']['out_trade_no']); // 开票地址
        // $billing = json_decode($billing, true);
        // if($billing['code'] == 'E0000'){
        //     $url = $billing['result']['ewmUrl'];
        //     return json_encode(array('status'=>1,'invoice_url'=>$url));
        // }else{
        //     return json_encode(array('status'=>2,'invoice_url'=>''));
        // }
    }
    
    /**
     * 通联 机构号-商户关联
     * 2022-05-24 10:14
     *
     * $institution_number 0524
     * $transaction_date 2022-03-25
     * $store_id 20209301460160674
     * ways_type_desc 微信支付
     * company 其它
     */
    public function mechanism_merchant(Request $request){
        //接参
        $data = $request->getContent();
        $data = json_decode($data, true);
        error_log(date('Y-m-d H:i:s')." 【通联调试】： ".json_encode($data)."\n\n", 3, "/www/wwwlogs/wft/". 'mechanism_merchant'.date('Ymd').".log");
        // 机构号
        $institution_number = isset($data['institution_number']) ? $data['institution_number'] : ''; 
        // 交易日期
        $transaction_date = isset($data['transaction_date']) ? $data['transaction_date'] : '';
        // 商户号
        $store_id = isset($data['merchant_id']) ? $data['merchant_id'] : ''; 
        // 支付方式
        $ways_type_desc = isset($data['ways_type_desc']) ? $data['ways_type_desc'] : '';
         // 通道类型
        $company = isset($data['company']) ? $data['company'] : '';
        // 查询机构号
        $allinpay_configs = Db::table('allinpay_configs')->where(['institution_number' => $institution_number])->first();
        $secret_key = isset($allinpay_configs->secret_key) ? $allinpay_configs->secret_key : ''; // key
        //验证传参
        // $check = $this->checks_md5($data, $secret_key); // 验证签名
        // if ($check['return_code'] == 'FALL') {
        //     return json_encode(["code" => 2, "msg" => "签名验证不通过"]);
        // }
        if(!$institution_number || !$transaction_date || !$secret_key){
            return json_encode(["code" => 2, "msg" => "该机构号或交易日期无效"]);
        }
        //查询条件
        $where = [];
        if($ways_type_desc){
            $where[] = ['ways_type_desc', '=', $ways_type_desc];
        }
        if($company){
            $where[] = ['company', '=', $company];
        }
        
        if(!$store_id){
            
            $institution = Db::table('mechanism_merchant')->where([ 'mechanism_id' => $institution_number])->select('merchant_id','now_time')->get(); // 商户id
            // $institution = Db::table('mechanism_merchant')->where([ 'merchant_id' => '20211118155217503420'])->select('merchant_id','now_time')->get(); // 商户id
            if(!$institution){
                return json_encode(["code" => 2, "msg" => "该机构号未绑定门店"]);
            }
            $institution = json_decode($institution, true);
            $institution_order=array();
            foreach($institution as $k=>$v){
                //绑定机构前流水去除
                if($v['now_time']>0){
                    $now_data=date('Y-m-d',$v['now_time']);
                    if($transaction_date>=$now_data){
                        $where[] = ['created_at', '>=', date($transaction_date) . ' 00:00:00'];
                    }else{
                        $where[] = ['created_at', '>=', date('Y-m-d H:i:s',$v['now_time'])];
                    }
                    $where[] = ['created_at', '<=', date($transaction_date) . ' 23:59:59'];
                    $model=Db::table('company_config')->where('model','2')->where('store_id', $v['merchant_id'])->get();
                    foreach($model as $k2=>$v2){
                        $store = DB::table('stores')->where('store_id', $v2->store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
                        $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
                        if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                            $store_ids[0] = $store->store_id;
                            $p_stores = json_decode($p_stores, true);
                            foreach($p_stores as $k1 => $v1){
                                $pay_ways=DB::table('store_pay_ways')->where('store_id', $v1['store_id'])->where('company', $v2->company)->where('status', 1)->select('company')->distinct()->first();
                                if(empty($pay_ways)){
                                    $store_ids[] = $v1['store_id'];
                                }
                            }
                        }else{
                            $store_ids[0] = $store->store_id;
                        }
                        $orders = Db::table('orders')->where($where)->where('company', $v2->company)->whereIn('store_id', $store_ids)->whereIn('pay_status', [1,6])->get();
                        $orders=json_decode($orders,true);
                        foreach($orders as $k3=>$v3){
                            $orders[$k3]['store_id']=$v2->store_id;
                        }
                        // unset($where);
                        // array_push($institution_order,$orders);

                        if(!empty($orders)){
                            array_push($institution_order,$orders);
                        }

                        //隔日退款订单处理
                        try {
                            $refundOrders = DB::table('refund_orders')
                                ->join('orders', 'refund_orders.out_trade_no', '=', 'orders.out_trade_no')
                                ->where(function ($query) use ($transaction_date, $now_data, $v, $v2, $store_ids) {
                                    $query->where('orders.company', $v2->company);
                                    $query->whereIn('orders.store_id', $store_ids);
                                    $startTime = date('Y-m-d H:i:s', $v['now_time']);
                                    if ($transaction_date >= $now_data) {
                                        $startTime = date($transaction_date) . ' 00:00:00';
                                    }
                                    $endTime = date($transaction_date) . ' 23:59:59';
                                    $query->whereBetween('refund_orders.created_at', [$startTime, $endTime]);
                                    $query->where('orders.created_at', '<=', $startTime);
                                    return $query;
                                })->select([
                                    'orders.store_id',
                                    'orders.device_id',
                                    'orders.created_at',
                                    'orders.refund_amount',
                                    'orders.rate',
                                    'orders.pay_status_desc',
                                    'orders.ways_type_desc',
                                    'orders.out_trade_no',
                                    'orders.trade_no',
                                    'orders.ways_type',
                                    'orders.company',
                                    'orders.updated_at',
                                    'orders.ways_source',
                                    "orders.pay_status",
                                ])->get();
                            if ($refundOrders && count($refundOrders) > 0) {
                                $refundOrders = json_decode($refundOrders, true);
                                foreach ($refundOrders as $refundIndex => $refundInfo) {
                                    $refundInfo['store_id'] = $v2->store_id;
                                    $refundInfo['total_amount'] = $refundInfo['refund_amount'];
                                    $refundInfo['fee_amount'] = bcmul($refundInfo['refund_amount'], bcdiv($refundInfo['rate'], 100, 4), 2);
//                                    unset($refundInfo['refund_amount']);
                                    unset($refundInfo['rate']);
                                    $refundOrders[$refundIndex] = $refundInfo;
                                }
                                array_push($institution_order,$refundOrders);
                            }
                        } catch (\Exception $e) {
                            $this->send("通联代扣通知\n>" . implode("\n>", [
                                "请求参数: <font color=\"warning\">" . json_encode($data) . "</font>",
                                "异常信息: <font color=\"warning\">" . $e->getMessage() . "</font>"
                            ]));
                        }
                    }
                }else{
                    $where[] = ['created_at', '>=', date($transaction_date) . ' 00:00:00'];
                    $where[] = ['created_at', '<=', date($transaction_date) . ' 23:59:59'];
                        
                    //代扣模式通道
                    $model=Db::table('company_config')->where('model','2')->where('store_id', $v['merchant_id'])->get();
                    
                    // $model=Db::table('company_config')->where('model','2')->where('store_id', $v['merchant_id'])
                    // ->orderBy('create_time','DESC')->limit(1)->get();
                    
                    foreach($model as $k2=>$v2){
                        $store = DB::table('stores')->where('store_id', $v2->store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
                        $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
                        if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                            $store_ids[0] = $store->store_id;
                            $p_stores = json_decode($p_stores, true);
                            foreach($p_stores as $k1 => $v1){
                                $pay_ways=DB::table('store_pay_ways')->where('store_id', $v1['store_id'])->where('company', $v2->company)->where('status', 1)->select('company')->distinct()->first();
                                if(empty($pay_ways)){
                                    $store_ids[] = $v1['store_id'];
                                }
                            }
                        }else{
                            $store_ids[0] = $store->store_id;
                        }
                        $orders = Db::table('orders')->where($where)->where('company', $v2->company)->whereIn('store_id', $store_ids)->whereIn('pay_status', [1,6])->get();
                        $orders=json_decode($orders,true);
                        foreach($orders as $k3=>$v3){
                            $orders[$k3]['store_id']=$v2->store_id;
                        }
                        // unset($where);
                        // array_push($institution_order,$orders);

                        if(!empty($orders)){
                            array_push($institution_order,$orders);
                        }
                        
                        //退款订单处理
                        try {
                            $refundOrders = DB::table('refund_orders')
                                ->join('orders', 'refund_orders.out_trade_no', '=', 'orders.out_trade_no')
                                ->where(function ($query) use ($transaction_date, $v, $v2, $store_ids) {
                                    $query->where('orders.company', $v2->company);
                                    $query->whereIn('orders.store_id', $store_ids);
                                    $startTime = date($transaction_date) . ' 00:00:00';
                                    $endTime = date($transaction_date) . ' 23:59:59';
                                    $query->whereBetween('refund_orders.created_at', [$startTime, $endTime]);
                                    $query->where('orders.created_at', '<=', $startTime);
                                    return $query;
                                })->select([
                                    'orders.store_id',
                                    'orders.device_id',
                                    'orders.created_at',
                                    'orders.refund_amount',
                                    'orders.rate',
                                    'orders.pay_status_desc',
                                    'orders.ways_type_desc',
                                    'orders.out_trade_no',
                                    'orders.trade_no',
                                    'orders.ways_type',
                                    'orders.company',
                                    'orders.updated_at',
                                    'orders.ways_source',
                                    "orders.pay_status",
                                ])->get();
                            if ($refundOrders && count($refundOrders) > 0) {
                                $refundOrders = json_decode($refundOrders, true);
                                foreach ($refundOrders as $refundIndex => $refundInfo) {
                                    $refundInfo['store_id'] = $v2->store_id;
                                    $refundInfo['total_amount'] = $refundInfo['refund_amount'];
                                    $refundInfo['fee_amount'] = bcmul($refundInfo['refund_amount'], bcdiv($refundInfo['rate'], 100, 4), 2);
//                                    unset($refundInfo['refund_amount']);
                                    unset($refundInfo['rate']);
                                    $refundOrders[$refundIndex] = $refundInfo;
                                }
                                array_push($institution_order,$refundOrders);
                            }
                        } catch (\Exception $e) {
                            $this->send("通联代扣通知\n>" . implode("\n>", [
                                "请求参数: <font color=\"warning\">" . json_encode($data) . "</font>",
                                "异常信息: <font color=\"warning\">" . $e->getMessage() . "</font>"
                            ]));
                        }
                    }
                }
                unset($store_ids);
            }
        }else{
            
            $institution = Db::table('mechanism_merchant')->where([ 'mechanism_id' => $institution_number, 'merchant_id' => $store_id])->select('merchant_id','now_time')->get(); // 商户id
            $institution = json_decode($institution, true);
            if(!$institution){
                return json_encode(["code" => 2, "msg" => "该机构号未绑定门店"]);
            }
            $institution_order=array();
             error_log(date('Y-m-d H:i:s')." 【通联调试2】： ".json_encode($institution)."\n\n", 3, "/www/wwwlogs/wft/". 'mechanism_merchant'.date('Ymd').".log");
            foreach($institution as $k=>$v){
                //绑定机构前流水去除
                if($v['now_time']>0){
                    $now_data=date('Y-m-d',$v['now_time']);
                    if($transaction_date>=$now_data){
                        $where[] = ['created_at', '>=', date($transaction_date) . ' 00:00:00'];
                    }else{
                        $where[] = ['created_at', '>=', date('Y-m-d H:i:s',$v['now_time'])];
                    }
                    $where[] = ['created_at', '<=', date($transaction_date) . ' 23:59:59'];
                    $model=Db::table('company_config')->where('model','2')->where('store_id', $v['merchant_id'])->get();
                    
                    // $model=Db::table('company_config')->where('model','2')->where('store_id', $v['merchant_id'])
                    // ->orderBy('create_time','DESC')->limit(1)->get();
                    
                    error_log(date('Y-m-d H:i:s')." 【通联调试36】： ".json_encode($model)."\n\n", 3, "/www/wwwlogs/wft/". 'mechanism_merchant'.date('Ymd').".log");
                    foreach($model as $k2=>$v2){
                        
                        $store = DB::table('stores')->where('store_id', $v2->store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
                        $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
                        if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                            $store_ids[0] = $store->store_id;
                            $p_stores = json_decode($p_stores, true);
                            foreach($p_stores as $k1 => $v1){
                                $pay_ways=DB::table('store_pay_ways')->where('store_id', $v1['store_id'])->where('company', $v2->company)->where('status', 1)->select('company')->distinct()->first();
                                if(empty($pay_ways)){
                                    $store_ids[] = $v1['store_id'];
                                }
                                if($store->store_id='202369115125143747'){
                                    $store_ids[] = $v1['store_id'];
                                }
                            }
                        }else{
                            $store_ids[0] = $store->store_id;
                        }
                         error_log(date('Y-m-d H:i:s')." 【通联通道】： ".json_encode([$v2])."\n\n", 3, "/tmp/". 'allpay'.date('Ymd').".log");

                        $orders = Db::table('orders')->where($where)->where('company', $v2->company)->whereIn('store_id', $store_ids)->whereIn('pay_status', [1,6])->get();
                        $orders=json_decode($orders,true);
                        foreach($orders as $k3=>$v3){
                            $orders[$k3]['store_id']=$v2->store_id;
                        }
                        // unset($where);
                        // array_push($institution_order,$orders);
                        
                        if(!empty($orders)){
                            array_push($institution_order,$orders);
                        }

                        //退款订单处理
                        try {
                            $refundOrders = DB::table('refund_orders')
                                ->join('orders', 'refund_orders.out_trade_no', '=', 'orders.out_trade_no')
                                ->where(function ($query) use ($transaction_date, $now_data, $v, $v2, $store_ids) {
                                    $query->where('orders.company', $v2->company);
                                    $query->whereIn('orders.store_id', $store_ids);
                                    $startTime = date('Y-m-d H:i:s', $v['now_time']);
                                    if ($transaction_date >= $now_data) {
                                        $startTime = date($transaction_date) . ' 00:00:00';
                                    }
                                    $endTime = date($transaction_date) . ' 23:59:59';
                                    $query->whereBetween('refund_orders.created_at', [$startTime, $endTime]);
                                    $query->where('orders.created_at', '<=', $startTime);
                                    return $query;
                                })->select([
                                    'orders.store_id',
                                    'orders.device_id',
                                    'orders.created_at',
                                    'orders.refund_amount',
                                    'orders.rate',
                                    'orders.pay_status_desc',
                                    'orders.ways_type_desc',
                                    'orders.out_trade_no',
                                    'orders.trade_no',
                                    'orders.ways_type',
                                    'orders.company',
                                    'orders.updated_at'
                                ])->get();
                            if ($refundOrders && count($refundOrders) > 0) {
                                $refundOrders = json_decode($refundOrders, true);
                                foreach ($refundOrders as $refundIndex => $refundInfo) {
                                    $refundInfo['store_id'] = $v2->store_id;
                                    $refundInfo['total_amount'] = $refundInfo['refund_amount'];
                                    $refundInfo['fee_amount'] = bcmul($refundInfo['refund_amount'], bcdiv($refundInfo['rate'], 100, 4), 2);
//                                    unset($refundInfo['refund_amount']);
                                    unset($refundInfo['rate']);
                                    $refundOrders[$refundIndex] = $refundInfo;
                                }
                                array_push($institution_order,$refundOrders);
                            }
                        } catch (\Exception $e) {
                            $this->send("通联代扣通知\n>" . implode("\n>", [
                                "请求参数: <font color=\"warning\">" . json_encode($data) . "</font>",
                                "异常信息: <font color=\"warning\">" . $e->getMessage() . "</font>"
                            ]));
                        }
                    }
                }else{
                    $where[] = ['created_at', '>=', date($transaction_date) . ' 00:00:00'];
                    $where[] = ['created_at', '<=', date($transaction_date) . ' 23:59:59'];
                        
                    //代扣模式通道
                    $model=Db::table('company_config')->where('model','2')->where('store_id', $v['merchant_id'])->get();
                    
                    // $model=Db::table('company_config')->where('model','2')->where('store_id', $v['merchant_id'])
                    // ->orderBy('create_time','DESC')->limit(1)->get();
                    
                    foreach($model as $k2=>$v2){
                        $store = DB::table('stores')->where('store_id', $v2->store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
                        $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
                        if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                            $store_ids[0] = $store->store_id;
                            $p_stores = json_decode($p_stores, true);
                            foreach($p_stores as $k1 => $v1){
                                $pay_ways=DB::table('store_pay_ways')->where('store_id', $v1['store_id'])->where('company', $v2->company)->where('status', 1)->select('company')->distinct()->first();
                                if(empty($pay_ways)){
                                    $store_ids[] = $v1['store_id'];
                                }
                            }
                        }else{
                            $store_ids[0] = $store->store_id;
                        }
                        $orders = Db::table('orders')->where($where)->where('company', $v2->company)->whereIn('store_id', $store_ids)->whereIn('pay_status', [1,6])->get();
                        $orders=json_decode($orders,true);
                        foreach($orders as $k3=>$v3){
                            $orders[$k3]['store_id']=$v2->store_id;
                        }
                        // unset($where);
                        // array_push($institution_order,$orders);

                        if(!empty($orders)){
                            array_push($institution_order,$orders);
                        }
                        
                        //退款订单处理
                        try {
                            $refundOrders = DB::table('refund_orders')
                                ->join('orders', 'refund_orders.out_trade_no', '=', 'orders.out_trade_no')
                                ->where(function ($query) use ($transaction_date, $v, $v2, $store_ids) {
                                    $query->where('orders.company', $v2->company);
                                    $query->whereIn('orders.store_id', $store_ids);
                                    $startTime = date($transaction_date) . ' 00:00:00';
                                    $endTime = date($transaction_date) . ' 23:59:59';
                                    $query->whereBetween('refund_orders.created_at', [$startTime, $endTime]);
                                    $query->where('orders.created_at', '<=', $startTime);
                                    return $query;
                                })->select([
                                    'orders.store_id',
                                    'orders.device_id',
                                    'orders.created_at',
                                    'orders.refund_amount',
                                    'orders.rate',
                                    'orders.pay_status_desc',
                                    'orders.ways_type_desc',
                                    'orders.out_trade_no',
                                    'orders.trade_no',
                                    'orders.ways_type',
                                    'orders.company',
                                    'orders.updated_at'
                                ])->get();
                            if ($refundOrders && count($refundOrders) > 0) {
                                $refundOrders = json_decode($refundOrders, true);
                                foreach ($refundOrders as $refundIndex => $refundInfo) {
                                    $refundInfo['store_id'] = $v2->store_id;
                                    $refundInfo['total_amount'] = $refundInfo['refund_amount'];
                                    $refundInfo['fee_amount'] = bcmul($refundInfo['refund_amount'], bcdiv($refundInfo['rate'], 100, 4), 2);
//                                    unset($refundInfo['refund_amount']);
                                    unset($refundInfo['rate']);
                                    $refundOrders[$refundIndex] = $refundInfo;
                                }
                                array_push($institution_order,$refundOrders);
                            }
                        } catch (\Exception $e) {
                            $this->send("通联代扣通知\n>" . implode("\n>", [
                                "请求参数: <font color=\"warning\">" . json_encode($data) . "</font>",
                                "异常信息: <font color=\"warning\">" . $e->getMessage() . "</font>"
                            ]));
                        }
                    }
                }
                unset($store_ids);
            }
            if(empty($institution_order[0])){
                return json_encode(["code" => 2, "msg" => "获取失败,当前商户无流水"], JSON_UNESCAPED_SLASHES);
            }
        }
        $count=0;
        foreach($institution_order as $k => $v){
            foreach ($v as $k1=>$v1){
//                if ($v1['ways_type_desc'] == '银联收款') {
//                    $v1['ways_type_desc'] = '云闪付支付';
//                }
                if($v1["ways_source"]=="alipay"){
                    $v1['ways_type_desc'] = '支付宝';
                }else if($v1["ways_source"]=="weixin"){
                    $v1['ways_type_desc'] = '微信支付';
                }else{
                    $v1['ways_type_desc'] = '云闪付支付';
                }
                if (isset($v1['refund_amount']) && !empty($v1['refund_amount']) && $v1['refund_amount'] != $v1['total_amount']) {

                    $v1['pay_status_desc'] = '支付成功';
                    $v1['total_amount'] = bcsub($v1['total_amount'] , $v1['refund_amount'], 2);
                }
                if(!in_array($v1["pay_status_desc"],["支付成功","已退款"])){
                    //重新渲染  "orders.pay_status",
                    if(isset($v1["pay_status"]) && $v1["pay_status"]==1){
                        $v1["pay_status_desc"]="支付成功";
                    }
                }
                unset($v1["pay_status"]);
                unset($v1["ways_source"]);
                $list[$count]['store_id'] = $v1['store_id'] . "\t";                        // 商户号
                $list[$count]['device_id'] = $v1['device_id'];                      // 终端号
                $list[$count]['created_at'] = $v1['created_at'];                    // 原订单时间
                $list[$count]['updated_at'] = $v1['updated_at'];                    // 交易时间
                $list[$count]['total_amount'] = $v1['total_amount'];                // 交易金额（分）
                $list[$count]['fee_amount'] = $v1['fee_amount'];                    // 交易手续费（分）
                $list[$count]['ways_type_desc'] = $v1['ways_type_desc'];            // 支付方式
                $list[$count]['pay_status_descs'] = $v1['pay_status_desc'];         // 交易状态
                $list[$count]['out_trade_no'] = $v1['out_trade_no'];                // 交易单号
                $list[$count]['original_refund_number'] = $v1['out_trade_no'];      // 退款原单号
                $list[$count]['terminal_serial_number'] = $v1['out_trade_no'];      // 终端流水号
                $list[$count]['trade_no'] = $v1['trade_no'] . "\t";                        // 渠道订单号
                $list[$count]['transaction_date'] = $transaction_date;             // 清算日期
                $list[$count]['company'] = $this->get_commany_name($v1['company']); // 通道类型
                $count+=1;
            }
        }
        //$transaction_date = $transaction_date.'123';
        unset($count);
        set_time_limit(0);
        $file_name = $transaction_date . $institution_number . $store_id . $ways_type_desc . $company . '.csv';
        $file_name_oss = 'http://' . env('ALIOSS_bucket') . '.' . env('ALIOSS_endpoint') . '/wft/' . $file_name;
        $is_file_name = Db::table('mechanism_merchant_oss')->where([ 'file_name' => $file_name_oss ])->value('file_name');
        if($is_file_name){
            return json_encode(["code" => 1, "msg" => "获取成功", "url" => $is_file_name], JSON_UNESCAPED_SLASHES);
        }
        $file_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/csv/" . $file_name;
        if( file_exists($file_path) ){
            unlink($file_path);
        }
        $file_path = "/uploads/csv/" . $file_name;
        $fp = fopen("." . $file_path, "a"); // 生成文件
        $limit = 10000;
        $calc = 0;
        $field = [
            'A' => ["ctime", "商户号"],
            'B' => ["full_name", "终端号"],
            'C' => ["full_name", "原订单时间"],
            'D' => ["full_name", "交易时间"],
            'E' => ["face_value", "交易金额（元）"],
            'F' => ["price_sgd", "交易手续费（元）"],
            'G' => ["err_code", "支付方式"],
            'H' => ["order_id", "交易状态"],
            'I' => ["client_id", "交易单号"],
            'J' => ["client_id", "退款原单号"],
            'K' => ["client_id", "终端流水号"],
            'L' => ["client_id", "渠道订单号"],
            'M' => ["client_id", "清算日期"],
            'N' => ["client_id", "通道类型"],
        ];
        foreach ($field as $k => $v) {
            $tit[] = "\xEF\xBB\xBF".$v[1];
        }
        fputcsv($fp, $tit);
        foreach ($list as $v) {
            $calc ++;
            if ($limit == $calc) {
                ob_flush();
                flush();
                $calc = 0;
            }
            foreach ($v as $_v) {
                $tarr[] = $_v;
            }
            fputcsv($fp, $tarr);
            unset($tarr);
        }
        unset($list);
        fclose($fp);

        $AccessKeyId = env('ALIOSS_AccessKeyId');
        $AccessKeySecret = env('ALIOSS_AccessKeySecret');
        $endpoint = env('ALIOSS_endpoint');
        $bucket = env('ALIOSS_bucket');
        $object = 'wft/' . $file_name;
        $content = file_get_contents(public_path() . $file_path);
        $ossClient = new \OSS\OssClient($AccessKeyId, $AccessKeySecret, $endpoint);
        $parameter = $data;
        $data = $ossClient->putObject($bucket, $object, $content);

        $url = $data['oss-request-url'];

        $unlink = unlink(public_path() . $file_path); // 删除本地图片
        $is_file_name = Db::table('mechanism_merchant_oss')->insert([ 'file_name' => $url ]);
        return json_encode(["code" => 1, "msg" => "获取成功", "url" => $url], JSON_UNESCAPED_SLASHES);
    }
    
    // 诺诺开票 通过code换取access_token
    function nuonuo_accessToken(Request $request){
        $code = $request->get('code', '');
        $taxnum = $request->get('taxnum', '');
        // print_r(2);die;
        
	    $appKey = "13985881";
		$appSecret = "5836FB60AB5A4D5D"; // 55wwxGWP
// 		$code = $code;
// 		$taxnum = $taxnum;
		$redirectUri = "https://pay.zgjindoufu.com/pay/nuonuo_accessToken";
// 		print_r(2);die;
		
		$res = $this->getISVToken($appKey, $appSecret, $code, $taxnum, $redirectUri);
        
        $res = json_decode($res, true);
        if( isset($res['access_token']) ){
        // echo '<pre>';
            $nuonuo_stores = DB::table('nuonuo_stores')->where([ 'userTax' => $taxnum ])->first();
            if($nuonuo_stores){
                DB::table('nuonuo_stores')->where([ 'userTax' => $taxnum ])->update(['access_token'=>$res['access_token']]);
            }
            
            print_r('access_token获取成功');die;
        }
        
        return $res;
        
    }
	
	/**
     * ISV应用获取accessToken
     * 
     * 返回报文:
     * {"access_token":"xxx","expires_in":86400,"refresh_token":"xxx","userId":"xxx","oauthUser":"{\"userName\":\"xxx\",\"registerType\":\"1\"}","userName":"xxx","registerType":"1"}
     *
     * @param appKey      开放平台appKey
     * @param appSecret   开放平台appSecret
     * @param code        临时授权码
     * @param taxnum      授权商户税号
     * @param redirectUri 授权回调地址
     * @throws NnuoException
	 * @return 成功时返回，其他抛异常
     */
	public static function getISVToken($appKey, $appSecret, $code, $taxnum, $redirectUri, $timeOut = 6)
	{
	    
		//检测必填参数
		self::checkParam($appKey, "AppKey不能为空");
		self::checkParam($appSecret, "AppSecret不能为空");
		self::checkParam($code, "code不能为空");
		self::checkParam($taxnum, "taxnum不能为空");
		self::checkParam($redirectUri, "redirectUri不能为空");
		
		$headers = array(
			"Content-Type: application/x-www-form-urlencoded"
		);
		$params = array(
			"client_id" => $appKey,
			"client_secret" => $appSecret,
			"code" => $code,
			"taxNum" => $taxnum,
			"redirect_uri" => $redirectUri,
			"grant_type" => "authorization_code"
		);
		
		$params = http_build_query($params);
		
		$url='https://open.nuonuo.com/accessToken';
		
		$res = self::postCurl($url, $params, $headers, $timeOut);
		return $res;
	}
	
	public static function checkParam($param, $errMsg) 
	{
		if(empty($param)) {
			throw new NnuoException($errMsg);
		}
	}
	
	/**
	 * 以post方式发起http调用
	 * 
	 * @param string $url  url
	 * @param array $params post参数
	 * @param int $second   url执行超时时间，默认30s
	 * @throws NnuoException
	 */
	private static function postCurl($url, $params, $headers = array(), $second = 30)
	{
	    
		$ch = curl_init();
		$curlVersion = curl_version();

		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
		curl_setopt($ch,CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

		if (!empty($headers)) {
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		}
		
		//运行curl
		$data = curl_exec($ch);
		//返回结果
		if($data) {
			curl_close($ch);
			return $data;
		} else {
			$error = curl_error($ch);
			curl_close($ch);
			throw new NnuoException("curl出错:$error");
		}
	}
	
	// 联动优势聚合支付 打款回调地址
    function test(Request $request){
        $data = $request->getContent(); // 获取传值
        file_put_contents('1116.log', var_export($data, true) . "\r\n", FILE_APPEND);
        return 2222;
    }
    //计划任务-自动审核通过门店
    public function day_stores(){
        $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
        $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
        
        $stores=DB::table('stores')->where($where)
            ->where("pid",0)
            ->where('status','2')->select('store_id')->get();
        foreach ($stores as $k=>$v){
            DB::table('stores')->where('store_id',$v->store_id)->update(array('status'=>'1','status_desc'=>'审核成功','admin_status'=>'1','admin_status_desc'=>'审核成功'));
        }
    }
    
    //计划任务-自动审核通过门店
    public function day_Smooth(){
        $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
        $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
        
        $stores=DB::table('wing_stores')->where($where)->where('is_smooth','0')->get();
        foreach ($stores as $k=>$v){
            $wing_store = DB::table('wing_stores')->where('id', $v->id)->first();
            $store = DB::table('stores')->where('store_id', $wing_store->store_id)->first();
            //  error_log(date('Y-m-d H:i:s')." 【测试】： ".json_encode([$store, $wing_store])."\n\n", 3, "/tmp/". 'test'.date('Ymd').".log");
            if (isset($store->people_phone)) {
                $obj = new \App\Api\Controllers\lianfu\PayController();
                $post_array=array(
                    'traceLogId'=>'wing'.time(),
                    'productNo'=>$store->people_phone,
                    'requestSystem'=>'API',
                    'merchantCode'=>$wing_store->merchantNo,
                    'signMerchantNo'=>$wing_store->institutionCode,
                    // 'agreeId'=>'20200909030100043101977613172787',
                    'agreeId'=>'20240321111652476783537426157568',
                    'signType'=>'S002',
                );
                $url='https://mapi.bestpay.com.cn/gapi/o2o/qdlPay/app/queryMerchantOpenFlagForAPI';
                $return = $obj->get_Smooth($post_array,$url);
                $return=json_decode($return,true);
                if($return['success']){
                    DB::table('wing_stores')->where('id', $v->id)->update(array('is_smooth'=>1));
                }
            }
        }
    }
    
    //计划任务-汇总门店及款台数据
    public function store_cash_count(){
        fastcgi_finish_request();
        $stores=DB::table('store_day')->select('store_id','settling_day','id')->limit(1000)->get()->toArray();
        foreach ($stores as $k=>$v){
            //查询总店是否有分店
            $store=DB::table('stores')->where(array('store_id'=>$v->store_id))->select('pid','id')->first();
            if($store->pid>0){
                //获取总店门店id
                $sub_store=DB::table('stores')->where(array('id'=>$store->pid))->select('store_id')->first();
            }
            $id=$store->id;
            $where[] = ['orders.created_at', '>=', $v->settling_day.' 00:00:00'];
            $where[] = ['orders.created_at', '<=', $v->settling_day.' 23:59:59'];
            //门店汇总
            $stores_data = DB::table('orders')->join('stores', function ($join) {$join->on('orders.store_id', '=', 'stores.store_id');})->whereIn('orders.pay_status', [1, 6])->where($where)->where(function ($query) use($id) {$query->where('stores.id', $id)->orwhere('stores.pid',$id);return $query;})->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total'),DB::raw('sum(orders.refund_amount) as refund_amount'),DB::raw('sum(orders.fee_amount) as fee_amount')])->first();
                
            //退款汇总
            $stores_data_refund = DB::table('orders')->join('stores', function ($join) {$join->on('orders.store_id', '=', 'stores.store_id');})->whereIn('orders.pay_status', [6])->where($where)->where(function ($query) use($id) {$query->where('stores.id', $id)->orwhere('stores.pid',$id);return $query;})->select([DB::raw('count(orders.out_trade_no) as total')])->first();
            //微信汇总
            $stores_data_wx= DB::table('orders')->join('stores', function ($join) {
                $join->on('orders.store_id', '=', 'stores.store_id');
            })
                ->whereIn('orders.pay_status', [1,6])
                ->where('orders.ways_source', 'weixin')
                ->where($where)
                ->where(function ($query) use($id) {
                    $query->where('stores.id', $id)->orwhere('stores.pid',$id);
                    return $query;
                })
                ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
                ->first();
                
            //支付宝汇总
            $stores_data_zfb= DB::table('orders')->join('stores', function ($join) {
                $join->on('orders.store_id', '=', 'stores.store_id');
            })
                ->whereIn('orders.pay_status', [1,6])
                ->where('orders.ways_source', 'alipay')
                ->where($where)
                ->where(function ($query) use($id) {
                    $query->where('stores.id', $id)->orwhere('stores.pid',$id);
                    return $query;
                })
                ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
                ->first();
                
            //云闪付汇总
            $stores_data_uni= DB::table('orders')->join('stores', function ($join) {
                $join->on('orders.store_id', '=', 'stores.store_id');
            })
                ->whereIn('orders.pay_status', [1,6])
                ->where('orders.ways_source', 'unionpay')
                ->where($where)
                ->where(function ($query) use($id) {
                    $query->where('stores.id', $id)->orwhere('stores.pid',$id);
                    return $query;
                })
                ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
                ->first();
                
            //翼支付汇总
            $stores_data_wing= DB::table('orders')->join('stores', function ($join) {
                $join->on('orders.store_id', '=', 'stores.store_id');
            })
                ->whereIn('orders.pay_status', [1,6])
                ->where('orders.ways_source', 'wingpay')
                ->where($where)
                ->where(function ($query) use($id) {
                    $query->where('stores.id', $id)->orwhere('stores.pid',$id);
                    return $query;
                })
                ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
                ->first();
            $refund_amount=$stores_data->refund_amount?$stores_data->refund_amount:0;
            $total_amount=$stores_data->total_amount?$stores_data->total_amount:0;
            $arr=array(
                'store_amount'=>$total_amount-$refund_amount,
                'refund_amount'=>$refund_amount,
                'fee_amount'=>$stores_data->fee_amount?$stores_data->fee_amount:0,
                'store_order_count'=>$stores_data->total,
                'refund_order_num'=>$stores_data_refund->total,
                'store_id'=> $v->store_id,
                'sub_storeid'=>$store->pid==0 ? 0 :$sub_store->store_id,
                'settling_day'=>$v->settling_day,
                'weixin_amount'=>$stores_data_wx->total_amount?$stores_data_wx->total_amount:0,
                'weixin_num'=>$stores_data_wx->total,
                'alipay_amount'=>$stores_data_zfb->total_amount?$stores_data_zfb->total_amount:0,
                'alipay_num'=>$stores_data_zfb->total,
                'unionpay_amount'=>$stores_data_uni->total_amount?$stores_data_uni->total_amount:0.00,
                'unionpay_num'=>$stores_data_uni->total,
                'bestpay_amount'=>$stores_data_wing->total_amount?$stores_data_wing->total_amount:0,
                'bestpay_num'=>$stores_data_wing->total,
                'created_at'=>time()
            );
            DB::table('stores_day_count')->insert($arr);
            $merchant_stores = DB::table('merchant_stores')->where('store_id',$v->store_id)->select('merchant_id')->get();
            foreach($merchant_stores as $key=>$val){
            //收银员汇总
            $stores_data_merch= DB::table('orders')->join('stores', function ($join) {
                $join->on('orders.store_id', '=', 'stores.store_id');
            })
                ->where('orders.merchant_id', $val->merchant_id)
                ->whereIn('orders.pay_status', [1,6])
                ->where($where)
                ->where(function ($query) use($id) {
                    $query->where('stores.id', $id)->orwhere('stores.pid',$id);
                    return $query;
                })
                ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
                ->first();
                $mer=array(
                    'store_id'=>$v->store_id,
                    'merchant_id'=>$val->merchant_id,
                    'merchant_money'=>$stores_data_merch->total_amount?$stores_data_merch->total_amount:0,
                    'merchant_num'=>$stores_data_merch->total,
                    'created_at'=>time(),
                    'settling_day'=>$v->settling_day,
                );
                DB::table('stores_cash_count')->insert($mer);
            }
            DB::table('store_day')->where('id',$v->id)->delete();
        }
    }
    
    public function yinkaUpdateToken ()
    {
        //$data = \App\Models\YinkaStore::where('expired_at', '<', time())->get();
        $data = \App\Models\YinkaStore::where('expired_at', '<', time())->whereNotNull('pri_key')->get();
        foreach ($data as $v) {
            \App\Api\Controllers\Yinka\BaseController::getInstance()->getToken($v);
        }
    }
    
    
    
    public function bill (Request $request)
    {
        $data = $request->getContent(); // 获取传值
        $data = json_decode($data, true);
        $check = $this->checks_md5($data, 'sQK4ZWjBQ7tHg'); // 验证签名
        if ($check['return_code'] == 'FALL') {
            return json_encode(["code" => 2, "msg" => "签名验证不通过"]);
        }
        $check_data = [
            'merchant_id' => '商户号',
            's_date' => '开始日期',
            'e_date' => '结束日期',
            'company' => '通道类型'
        ];
        $check = $this->check_required($data, $check_data);
        if ($check) {
            return json_encode(["code" => 2, "msg" => $check]);
        }

        if (((strtotime($data['e_date']) - strtotime($data['s_date'])) / 86400) >= 32) {
            return json_encode(["code" => 2, "msg" => '时间不能超过一个月']);
        }


        if ($data['company'] == 'psbc') {
            $storeId = \App\Models\LianfuyoupayStores::where(['apikey' => $data['merchant_id']])->value('store_id');
            $pid = \App\Models\Store::where(['store_id' => $storeId])->value('id');
            $arr = \App\Models\Store::where(['pid' => $pid])->select('store_id')->get();
            $ids[] = $storeId;
            foreach ($arr as $v) {
                $ids[] = $v->store_id;
            }
            if ($ids) {
                $where[] = ['created_at', '>=', date($data['s_date']) . ' 00:00:00'];
                $where[] = ['created_at', '<=', date($data['e_date']) . ' 23:59:59'];
                $ret = Order::where($where)->whereIn('store_id', $ids)
                    ->whereIn('pay_status', [1])
                    ->select('store_name', 'out_trade_no', 'trade_no', 'total_amount','pay_amount' ,'pay_time')->get();
                return json_encode(["code" => 1, "msg" => '成功', 'list' => $ret]);
            }
        }
    }
    public function check_required($check, $data)
    {
        $rules = [];
        $attributes = [];

        foreach ($data as $k => $v) {
            $rules[$k] = 'required';
            $attributes[$k] = $v;
        }

        $messages = [
            'required' => ':attribute不能为空'
        ];

        $validator =  \Illuminate\Support\Facades\Validator::make($check, $rules, $messages, $attributes);
        $message = $validator->getMessageBag();

        return $message->first();
    }
    

    //计划任务-等待支付订单每日02：00同步前一天的数据
    public function update_waiting_order()
    {
        $obj = DB::table('orders');
        $where = [];
        $where[] = ['pay_status', '=', 2];
        // 获取昨天 00:00:00
        $yesterdayStart = date('Y-m-d 00:00:00', strtotime('-1 day'));
//        $yesterdayStart = date('Y-m-d 00:00:00');
        // 获取昨天 23:59:59
        $yesterdayEnd = date('Y-m-d 23:59:59', strtotime('-1 day'));
//        $yesterdayEnd = date('Y-m-d 23:59:59');
        $where[] = ['created_at', '>=', $yesterdayStart];
        $where[] = ['created_at', '<=', $yesterdayEnd];
        $obj = $obj->where($where)->orderBy('created_at', 'desc');
        $results = $obj->get();
        if($results){
            $returnData = [];
            $mergedArray = json_decode(json_encode($results),true);
            foreach ($mergedArray as $item) {
                $returnData[] = $this->handleWaitingOrder($item['out_trade_no'],$item['store_id']);
            }
            return $returnData;
        }
    }

    //等待支付订单状态更新
    public  function  handleWaitingOrder($out_trade_no,$store_id)
    {
        $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
        $b = str_ireplace($a, "", $out_trade_no);
        $day = substr($b, 0, 8);
        $table = 'orders_' . $day;

        if (Schema::hasTable($table)) {
            $order = DB::table($table)->where('out_trade_no', $out_trade_no)
                ->where('store_id', $store_id)
                ->first();
        } else {
            $order = DB::table('orders')->where('out_trade_no', $out_trade_no)
                ->where('store_id', $store_id)
                ->first();
        }
        if (!$order) {
            return json_encode(['status' => 2, 'message' => "订单号不存在"]);
        }
        if ($order->pay_status == 6) {
            return json_encode(['status' => 2, 'message' => "退款订单无法同步状态"]);
        }

        if($order->pay_status==1){
            return json_encode(['status' => 2, 'message' => "支付成功订单无法同步状态"]);
        }

        $data = [
            'out_trade_no' => $order->out_trade_no,
            'store_id' => $order->store_id,
            'ways_type' => $order->ways_type,
            'config_id' => $order->config_id,
            'table' => $table,
        ];
        $objData = new OrderController();
        $return = $objData->order_foreach_public($data);
        //处理支付失败订单 1
        $return1 = json_decode($return, true);
        if ($return1['pay_status'] == '3' || $return1['pay_status'] == 3) {
            if (!empty($return1['data']['out_trade_no'])) {
                (new \App\Services\Pay\PayService())->closeOrder($return1['data']['out_trade_no']);
            }
        }
        //处理支付失败订单
        return $return;
    }
    
    
    
}